<template>
    <div>

        <el-upload ref="upload" class="upload-demo" action="http://localhost:8080/api/book/uploadExcel" :limit="1"
            :before-upload="beforeUpload" :on-success="handleSuccess" :on-error="uploadError" :file-list="fileList">
            <el-button type="primary">导入</el-button>
        </el-upload>
        <el-button type="success" @click="downloadExcel">导出</el-button>

    </div>
</template>

<script>
export default {
    name: 'book',
    data() {
        return {
            fileList: []
        }
    },
    methods: {
        //导出
        downloadExcel() {
            this.$axios({
                method: 'get',
                url: ' http://localhost:8080/api/book/downloadExcel',
                responseType: 'blob'
            }).then((res) => {
                let filename = decodeURIComponent(res.headers.get('X-Filename'));
                const url = window.URL.createObjectURL(new Blob([res.data]))
                const link = document.createElement('a')
                link.href = url
                link.setAttribute('download', filename)
                document.body.appendChild(link)
                link.click()
            })

        },
        //上传之前调用：校验类型、大小
        beforeUpload(file) {
            console.log("file.type:" + file.type);

            const fileSize = file.size / Math.pow(2, 20);
            if (file.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
                this.$message.error('只能上传excel文件')
                return false;
            }

            if (fileSize > 10) {
                this.$message.error("图片不能超过10MB")
                return false;
            }

            return true;
        },
        //图片上传成功之后：将上传图片的数据添加到fileList
        handleSuccess(response, file, fileList) {
            // 根据后端返回的数据修改fileList集合
            console.log("图片上传成功之后response:" + JSON.stringify(response));

        },

        //上传失败的逻辑
        uploadError(err, file, fileList) {
            this.$message({
                message: err.message,
                type: "error",
            });
        },

    }
}
</script>

<style></style>